<!-- 饼图 -->
<template>
  <div class="echarts-info" :style="{ height: height, width: width }" :id="'canvas-box-pic1'+number"></div>
</template>

<script lang="ts" name="BasicEchartsPie" setup>
import {getCurrentInstance, nextTick, onBeforeUnmount, onMounted, reactive, ref, shallowRef, watch} from "vue";
import {debounce} from "lodash";
import {fontSizeRem} from "@/utils/baseCfg";
const { proxy } = getCurrentInstance() as any //类型可以为任意类型

const props = defineProps({
  width: {
    type: String,
    default: "100%",
  },
  height: {
    type: String,
    default: "100%",
  },
  title: {
    type: String,
    default: "总计",
  },
  titleStyle:{
    type: Object,
    default: () => {
      return {
        titleSize: fontSizeRem(26),
        subtitleSize: fontSizeRem(16),
      }
    },
  },
  showLabel:{
    type: Boolean,
    default: true,
  },
  showLegend:{
    type: Boolean,
    default: true,
  },
  spe:{
    type: Boolean,
    default: true,
  },
  chartData: {
    type: Object,
    default: () => {
      return {
        name: [],
      }
    },
    required: true, //传入的报表数据
  },
  graphic:{
    type: Object,
    default: () => {
      return {
        top: 75,
        width: 120,
        height: 120
      }
    },
  },
})

// 报表信息
const eCharts = proxy.$ECharts
let chart = shallowRef<any>();
let colors = reactive([
  "rgba(38, 224, 174, 1)",
  "rgba(255, 76, 76, 1)",
  "rgba(255, 157, 85, 1)",
  "rgba(108, 232, 172, 1)",
  "rgba(245, 212, 70, 1)",
  "rgba(54, 153, 255, 1)",
  "rgba(0, 255, 255, 1)",
  "rgba(255, 164, 67, 1)",
  "rgba(158, 136, 255, 1)",
  "rgba(184, 122, 1, 1)",
  "rgba(6, 70, 255, 1)",
  "rgba(245, 212, 70, 1)",
],); // pic颜色
let number = ref(Math.random() + 1); // 报表id
watch(
    () => props.chartData,
    async () => {
      await nextTick()
      initChart()
    },
    {
      deep: true
    }
)

const resizeHandler = () => {
  chart.value.resize()
}

const resizeHandlerOrigin = debounce(resizeHandler, 500)

// 初始化报表
const initChart = () =>{
  chart.value = eCharts.getInstanceByDom(document.getElementById(`canvas-box-pic1${number.value}`))
  if (chart.value === undefined) {
    chart.value = eCharts.init(document.getElementById(`canvas-box-pic1${number.value}`));
  }
  chart.value.clear();
  setOptions();
}
// 图表配置项
const setOptions = ()=> {
  const options = {
    tooltip: {
      trigger: 'item',
      formatter: function (params){
        const {data,percent} = params
        return `${data.name}:${data.value},占比：${percent}%`
      },
    },
    color: colors,
    graphic: [{
        type: 'image',
        id: 'backgroundImage',
        left: 'center',
        top: 'center',
        style: {
          image: new URL(`../assets/icons/pie-bg.png`, import.meta.url).href, // 背景图片的路径或URL
          width: fontSizeRem(props.graphic.width),  // 图片的宽度，可以设置为具体像素值或百分比
          height: fontSizeRem(props.graphic.height), // 图片的高度，可以设置为具体像素值或百分比
          opacity: 1    // 图片的透明度，范围从0（完全透明）到1（完全不透明）
        },
        z: -10,            // 控制图形元素的堆叠顺序，值越小越先绘制，被其他元素覆盖的可能性越大
        enterFrom: {
          // 淡入
          style: { opacity: 0 },
          // 从左飞入
          x: 0
        },
      },
      {
        type: 'text',
        left: 'center',
        top: '42%',
        style: {
          text: props.chartData?.count ? props.chartData?.count : 0,
          textAlign: 'center',
          fill: 'rgba(255, 199, 103, 1)',  // 字体颜色
          fontSize: props.titleStyle.titleSize,  // 字体大小
          fontFamily: 'din-bold'
        }
      },
      {
        type: 'text',
        left: 'center',
        top: '58%',
        style: {
          text: '总计',
          textAlign: 'center',
          fill: '#FFFFFF',  // 字体颜色
          fontSize: props.titleStyle.subtitleSize,  // 字体大小
          fontFamily: 'din-bold'
        }
      }
    ],
    series: [
      {
        name: props.title,
        type: 'pie',
        radius: ['50%', '60%'],
        padAngle: 2,
        startAngle: 200,
        label: {
          show: props.showLabel,
          position: props.chartData?.showLabel === false ? 'inner' : 'outside',
          rich:{
            label:{
              color:'rgba(255, 255, 255, 1)',
              fontSize: fontSizeRem(16),
              fontWeight:'bold',
            },
            value:{
              fontSize: fontSizeRem(26),
              color: 'inherit',
              fontFamily: 'DIN-Medium'
            },
            value1:{
              fontSize: fontSizeRem(12),
              color:'rgba(255, 255, 255, 1)',
              fontWeight:'bold',
            }
          },
          formatter: function (params){
            const {data,percent} = params
            if(props.chartData?.showLabel === false){
              return `{value1| ${percent}%}`
            }else{
              return `{label|${data.name}} {value|${data.value}}\n{label|(${percent}%)}`
            }
          },
        },
        labelLine: {
          show: true,
          length: fontSizeRem(5),  // 第一段长度
          length2: fontSizeRem(100),   // 第二段长度，0表示直接连接到标签边缘
          lineStyle: {
            width: 2,      // 引导线宽度
            type: 'solid'  // 引导线类型，默认为实线
          }
        },
        emphasis: {
          label: {
            show: true,
            fontSize: fontSizeRem(12),
            formatter: '{b}{d}%',
          },
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 2,
            shadowColor: 'rgba(0, 0, 0, .5)'
          }
        },
        data: props.chartData?.dataList ?? []
      }
    ]
  }
  chart.value.setOption(options);
}

window.addEventListener('resize', resizeHandlerOrigin)
onMounted(async () => {
  // 初始化报表
  await nextTick()
  initChart();
})

onBeforeUnmount(()=>{
  window.removeEventListener('resize', resizeHandlerOrigin)
  // 页面销毁时 销毁图表
  if (!chart) {
    return;
  }
  chart.value.dispose();
  chart.value = null;
})
</script>

<style scoped>

</style>